<template>
  <div v-if="articles && articles.length">
  <a-layout>
    <a-layout-content>
      
        <a-card v-for="article in articles" :key="article.id" class="article-card">
          <h2>{{ article.title }}</h2>
          <p><strong>预览:</strong> {{ article.preview }}</p>
          <a-button type="link" @click="viewDetail(article.id!)">阅读更多</a-button>
        </a-card>
      

    </a-layout-content>
  </a-layout>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from '../axios';
import { useAuthStore } from '../store/auth';
import type { Article } from "../types/Article";
import { message } from 'ant-design-vue';

const articles = ref<Article[]>([]);
const router = useRouter();
const authStore = useAuthStore();

// 定义接口以描述接口返回的数据结构
interface ApiResponse {
  data: Article[];
}
const fetchArticles = async () => {
  try {
    const response = await axios.get<ApiResponse>('/articles');
    articles.value = response.data.data;
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    if (axiosError.response?.data?.code === 500) {
      message.error(axiosError.response.data.message || '公告不存在');
    } else {
      message.error('获取公告失败，请重试。');
    }
  }
};

const viewDetail = (id: string) => {
  if (!authStore.isAuthenticated) {
    message.error('请先登录后再查看');
    return;
  }
  router.push({ name: 'NewsDetail', params: { id } });
};



onMounted(fetchArticles);
</script>

<style scoped>
.article-card {
  margin: 20px 0;
}

.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}
</style>